<?php
/**
 * @brief Ecmcpal支付插件类
 * @class Ecmcpal
 * @package App
 * @subpackage  Driver.Payment
 * @author cjli
 */
class Ecmcpal extends Payment implements Payment_Interface
{
	public function __construct()
	{
		$this->_paymentInfo = PaymentModel::get_payment_info('Ecmcpal');
	}
	
  public function getSettingFields()
  {
    return array(
      'MerNo' => '商户帐号',
      'MD5key' => '商户密钥',
      'Currency' => array(
        'name' => '支付货币',
        'type' => 'select',
        'options' => array(
          'USD' => '美元',
          'AUD' => '澳元',
          'CAD' => '加元',
          'EUR' => '欧元',
          'GBP' => '英镑',
          'JPY' => '日元',
          'HKD' => '港元',
        ),
        'default' => 'USD',
      ),
    );
  }

  public function getSubmitForm($orderInfo)
  {
  	global $language_id;
    $dateStr = date('Ymd', time());
    $orderAmount = $orderInfo['pay_amount'];
    
 	 	$c = SiteModel::get_currency_info($orderInfo['currency']);
		if (isset($c['exchange']) && $c['exchange']) {
		   $Amount = $c['exchange'] * $orderAmount;
		 }
		 
    $MD5key = $this->_paymentInfo['config']['MD5key'];                             //MD5私钥
    $MerNo = $this->_paymentInfo['config']['MerNo'];						                   //商户号
     $BillNo = $orderInfo['order_sn'];
		 $Currency = $this->_paymentInfo['config']['Currency'];                         //币种
     
		 $DispAmount= 0;                                           //外币金额
			$lang_id = isset($orderInfo['language_id']) ? $orderInfo['language_id'] : $language_id;
      $languageInfo = SiteModel::get_language_info($lang_id);
		 if ($languageInfo['code'] = "fr") {
			 $Language = '3';
		 }
		 else {
			 $Language = '2';
		 }
         $ReturnURL = url('payment/callback', array('pay' => 'Ecmcpal'));    //返回地址
         $Remark = 'ecmcpal'; //备注
         $md5src = $MerNo.$BillNo.$Currency.$Amount.$Language.$ReturnURL.$MD5key; //校验源字符串
         $Md5info = strtoupper(md5($md5src));                                     //MD5检验结果

			$shippingFirstName = $orderInfo['delivery_first_name'];
			$shippingLastName = $orderInfo['delivery_last_name'];
			$shippingEmail = $orderInfo['delivery_email']; 
			$shippingPhone = $orderInfo['delivery_phone']; 
			$shippingZipcode =$orderInfo['delivery_postcode']; 
			//$shippingAddress = $order['address'].'&nbsp;&nbsp;'.$order['address1'].'&nbsp;&nbsp;'.$order['address2'];
	
			$shippingAddress = $orderInfo['delivery_address'];
			
			$shippingAddress .= $orderInfo['delivery_address2'] ? '&nbsp;&nbsp;'.$orderInfo['delivery_address2'] : null;
			$shippingAddress .= $orderInfo['delivery_address3'] ? '&nbsp;&nbsp;'.$orderInfo['delivery_address3'] : null;

			$shippingCity = $orderInfo['delivery_city'];
			$shippingState = $orderInfo['delivery_province'];
			
			//物品信息
			$goods_list =OrderModel::get_order_product_list($orderInfo['id']);
			foreach ($goods_list AS $key => $goods){
			//    $prouductsinfo=$prouductsinfo.$goods['goods_number'].'*'.$goods['goods_name'].'*'.$goods['goods_price'].'|';
				$prouductsinfo .= $goods['qty'].'*'.$goods['product_sn'].'|';
			}
			$prouductsinfo = substr($prouductsinfo,0,-1);
			
			$button = '<form id="frm" action="http://www.dudufr.com/ecmcpal_from.php" method="post" target="_blank">'.
		//$button = '<form action="https://www.ecmcpal.com/personal/pays" method="post"target="_blank">'.
                    "  <input type='hidden' name='MerNo' value='". $MerNo ."'>".
                    "  <input type='hidden' name='Currency' value='". $Currency ."'>".
                    "  <input type='hidden' name='BillNo' value='". $BillNo ."'>".
                    "  <input type='hidden' name='Amount' value='". $Amount ."'>".
                    "  <input type='hidden' name='ReturnURL' value='". $ReturnURL ."'>".
                    "  <input type='hidden' name='Language' value='". $Language ."'>".
                    "  <input type='hidden' name='Md5info' value='". $Md5info ."'>".
                    "  <input type='hidden' name='remark' value='". $Remark ."'>".
					"  <input type='hidden' name='shippingFirstName' value='". $shippingFirstName ."'>".
					"  <input type='hidden' name='shippingEmail' value='". $shippingEmail ."'>".
					"  <input type='hidden' name='shippingPhone' value='". $shippingPhone ."'>".
					"  <input type='hidden' name='shippingZipcode' value='". $shippingZipcode ."'>".
					"  <input type='hidden' name='shippingAddress' value='". $shippingAddress ."'>".
					"  <input type='hidden' name='shippingCity' value='". $shippingCity ."'>".
					"  <input type='hidden' name='shippingState' value='". $shippingState ."'>".
					"  <input type='hidden' name='products' value='".$prouductsinfo."'>".
					"  <input type='hidden' name='sitename' value='www.google.fr'>".
                    "  <input class='small_pay_button' type='submit' name='b1' value='" . L('_PAY_NOW_') . "'>".
                    "</form>";

        return $button;
  }
  
 	 private function checkGet()
  	{
	  	$dingdanhao_ecmcpal = $_REQUEST["BillNo"];     //订单号
			if (ctype_alnum($dingdanhao_ecmcpal)) {
		        $BillNo = $dingdanhao_ecmcpal;
			}
			else {
				$BillNo = '';
			}
        $Currency = $_REQUEST["Currency"]; //币种
        $Amount = $_REQUEST["Amount"];     //金额
        $Succeed = $_REQUEST["Succeed"];   //支付状态
        $TradeNo = $_REQUEST["TradeNo"];   //支付平台流水号
        $Result = $_REQUEST["Result"];     //支付结果
        $MD5info = $_REQUEST["MD5info"];   //取得的MD5校验信息
        
        $MD5key = $this->_paymentInfo['config']['MD5key'];                         //MD5私钥
        $md5src = $BillNo.$Currency.$Amount.$Succeed.$MD5key; //校验源字符串
        $md5sign = strtoupper(md5($md5src));                  //MD5检验结果
		$real_ip = real_ip();

		/* 验证 */
        if ($MD5info!= $md5sign)
        {
            return false;
        }

   	$this->logw_ecmcpal($BillNo,$Amount,$Currency,$Succeed,$MD5info,$md5sign,$real_ip,$Result);
   	
   	$c = SiteModel::get_currency_info($_REQUEST['Currency']);
		if (isset($c['exchange']) && $c['exchange']) {
	   	$Amount = $Amount / $c['exchange'];
	 	}
	 	$_GET["Amount"] = $Amount;
    	
		if ($Succeed == '88')
			{
				return true;
				//return '100';
			}
		else if($Succeed == '19')
			{
				return true;
				//return '300';	//返回300表示付款结果正在处理中
			}
		else
			{
				return false;
			}
  }

  public function callback()
  {
    if ($this->checkGet()) {
      $result = array(
        'verified' => true,
        'paidAmount' => $_REQUEST["Amount"],
        'paymentId' => $_REQUEST['code'],
        'orderNumber' => $_REQUEST["BillNo"],
        'updateOrderStatus' => true,
        'message' => $_REQUEST["Result"],
      );
    } else {
      $result = array(
        'verified' => false,
      	'message' => $_REQUEST["Result"],
      );
    }
    return $result;
  }

  
	private function logw_ecmcpal($BillNo,$Amount,$Currency,$Succeed,$MD5info,$md5sign,$real_ip,$Result)
	{
		$james=fopen(LOG_PATH . "payment/ecmcpal.log","a+");
		fwrite($james,"\r\n".date("Y-m-d H:i:s")."|BillNo[ ".$BillNo." ]|Amount[ ".$Amount." ]|Currency[ ".$Currency." ]|Succeed[ ".$Succeed." ]|MD5info[ ".$MD5info."||".$md5sign." ]|real_ip[ ".$real_ip." ]|Result[ ".$Result." ]"."\r\n");
		fclose($james);
	}
}
